# -*- coding: utf-8 -*-
#===============================================================================
# Koro Business Environment
# Copyright (C) 2008  Antonio Corroppoli
#
#This file is part of Koro BE.
# 
# Koro BE is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
# 
# Koro BE is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with Koro BE; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
#===============================================================================

print 'koro __init__'
# Package initialisation
import sys
from koro import __version__
version = __version__.VERSION_STRING
version_info=__version__.VERSION_INFO

from koro.settings import Settings
ksettings = Settings()
from koro import util
from koro.db import persister
from koro.core import model
__controller=None


def application_factory():
    global __controller
    assert (__controller is None),Exception("Controller esistente!")
    from koro.core import controller
    __controller=controller.Controller()
    return __controller

def _get_controller():
    return __controller

def _get_option(opt):
    return __controller.get_option(opt)

def _get_options():
    return __controller.get_options()
#from koro.core import interface,context,controller
#from gControllers import MController 09-05-07
#__all__=['controllers',]
#import ui


#===============================================================================
# Configuration
#===============================================================================
class Configuration(object):
    def __init__(self):
        self.modules = []
        self.context_page_map = {}#mappa un context su una page
        self.id_context_map = {}#mappa un id di menu su un context
        self.name_context_map = {}#mappa un nome context su una classe context
        self.options_view = util.KoroList()#lista dei Panels delle opzioni
        self.dati_azienda = None
    
    def __getitem__(self,key):
        try:
            return self.id_context_map[key]
        except:
            pass
        try:
            return self.context_page_map[key]
        except:
            pass        
        raise KeyError('{0}: valore chiave errato!'.format(key))
    
    def to_context(self,name):
        '''Restituisce una classe di contesto.
        Il parametro name è una chiave (stringa) mappata su una classe contesto.
        Se la ricerca della chiave fallisce, la funzione restituisce il paramentro name.'''
        if not name in self.name_context_map:
            return name
        return self.name_context_map[name]           
    
    def _load_available_modules(self):
        import os
        from koro import modules
        path=modules.__path__[0]
        self.modules=model.Modules()
        modules_name=os.listdir(path)
        #modules_name.remove('documenti')
        for name in modules_name:             
            if (not name.startswith('.') and #fix: non considere la cartella .svn
                os.path.isdir(os.path.join(path,name))):
                self.modules.add(model.Module(name))
    
    def _load_modules(self):        
        self.modules=[]
        self._load_available_modules()
        persister.ObjectPersister.use(ksettings.KOROBE_CFG)
        ENABLED_MODULES = util.default_if_none(persister.ObjectPersister.get('ENABLED_MODULES'),[])
        for module_name in ENABLED_MODULES:
            self.modules.load(module_name)            
    
    def configure(self):
        #from koro.ui.wxgui.korogui import ID_OPZIONI_PAGE
        #reload(settings)
        from koro.ui import view
        from koro.core import context        
        self._load_modules()
        for item in self.modules.enabled():            
            self.context_page_map.update(item.module.context_map())
            self.id_context_map.update(item.module.id_map())
            self.name_context_map.update(item.module.name_map())
            self.options_view.append(item.module.option_view())
            
        #configurazione opzioni
        self.context_page_map.update({context.OpzioniContext:(view.get_instance().get_option_page(),(tuple(self.options_view),),{'modules':self.modules,})})
        self.id_context_map.update({view.get_instance().get_options_page_ID():context.OpzioniContext})
        self.name_context_map.update({'OPZIONI':context.OpzioniContext})
    
    def configure_orm(self,mapper,relation,metadata,Table):
        for item in self.modules.enabled():
            item.module.or_mapping(mapper,relation,metadata,Table)
    
    def configure_view(self,menubar):
        for item in self.modules.enabled():
            item.module.menu(menubar) 
    
        
